﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ForumServer;
using System.Threading;
using System.Collections;
using ForumServer.Forum;
using ForumLibrary;
using ForumLibrary.Data;

namespace ForumGUI
{

    public partial class PostsFrame : Form
    {
        private String                              _forum;
        private String                              _threadName;
        private ClientController                    _controller;
        private ForumManager                       _manager;
        public String ThreadName { get{return _threadName;} }
        public String ForumName { get { return _forum; } }

        public PostsFrame(ClientController controller, ref ForumManager manager,String forum, String threadName)
        {
            InitializeComponent();
            
            _controller = controller;
            // push form
            _controller.pushForm(this);
            _threadName = threadName;
            _forum = forum;
            _manager = manager;
            HeaderLabel.Text = _threadName;
            String toParse = "";
            try 
	        {	        
		        toParse = manager.getThreadDetails(forum, threadName);
	        }
	        catch (Exception)
	        {
                _controller.Logger.Info("Could not get Thread" + threadName + "details from forum " + forum);
                MessageBox.Show("Server is down. Please Logout and try again in a few minutes");
	        }
            char[] delimiter = { '~' };
            String[] parse = toParse.Split('~');
            ContentLabel.Text = "";
            informationLabel.Text = "";
            try
            {
                ContentLabel.Text += parse[1] + '\n';
                informationLabel.Text += "Number of replies: " + parse[2] + '\n';
                informationLabel.Text += "Number of views: " + parse[3] + '\n';
                informationLabel.Text += "Create by: " + parse[4] + '\n';
                informationLabel.Text += "Created at: " + parse[5] + '\n';
                informationLabel.Text += "Last change at: " + parse[6] + '\n';
            }
            catch (IndexOutOfRangeException)
            {
                MessageBox.Show("ERROR!!! wrong parsing.");
            }
            refreshPostList();
            

        }
        public void refreshPostList()
        {
            PostsListBox.Items.Clear();
            String toParse = "";
           try 
	        {
                toParse = (string)_manager.getPosts(_forum, _threadName);
	        }
	        catch (Exception)
	        {
                _controller.Logger.Info("Could not get Post Headers " + _threadName + "details from forum " + _forum);
                MessageBox.Show("Server is down. Please Logout and try again in a few minutes");
	        } 
            String[] parse = toParse.Split('~');
            foreach (String s in parse)
            {
                String[] headers = s.Split('_');
                if (!String.IsNullOrEmpty(s))
                {
                    PostsListBox.Items.Add(headers[0]);
                }
            }

        }
        private bool containHeader(String header)
        {
            for (int i = 0; i < PostsListBox.Items.Count; i++ )
            {
                if (header.Equals((String)PostsListBox.Items[i]))
                    return true;
            }
            return false;
        }

        private void AddPostButton_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(NewPostHeader.Text))
            {
                MessageBox.Show("Please enter header for the post");
                return;
            }
            if (String.IsNullOrEmpty(NewPostContent.Text))
            {
                MessageBox.Show("Please enter the content of the post");
                return;
            }
            if (containHeader(NewPostHeader.Text))
            {
                MessageBox.Show("Post header already exist!!!");
                return;
            }
            String res;
            try 
	        {
                res = _manager.addPost(_controller.Username, _forum, _threadName, NewPostHeader.Text, NewPostContent.Text);
	        }
	        catch (Exception)
	        {
                _controller.Logger.Info("Could not add Post " + _threadName + "details from forum " + _forum + ",for user" + _controller.Username);
                MessageBox.Show("Server is down. Please Logout and try again in a few minutes");
	        }

            refreshPostList();
            NewPostContent.Text = "";
            NewPostHeader.Text = "";

        }

        private void EditPostButton_Click(object sender, EventArgs e)
        {
            if (PostsListBox.Items.Count == 0)
            {
                MessageBox.Show("There are no post to edit");
                return;
            }
            if (PostsListBox.SelectedIndex < 0 || PostsListBox.SelectedIndex >= PostsListBox.Items.Count)
            {
                MessageBox.Show("Please select post.");
                return;
            }
            String post = (String)PostsListBox.Items[PostsListBox.SelectedIndex];
            if (isPostCreatorOrModifier(post))
            {
                String res = "";
                try
                {
                    res = _manager.getPostDetails(_forum, _threadName, post);
                }
                catch (Exception)
                {
                    _controller.Logger.Info("Could not get Post " + post + "details from forum " + _forum + ",for thread" + _threadName);
                    MessageBox.Show("Server is down. Please Logout and try again in a few minutes");
                }


                String[] parse = res.Split('~');
                this.Visible = false;
                new ViewEditPost(_controller, ref _manager, _controller.Username, _forum, _threadName, parse[0], parse[1], false).Visible = true;
            }
            else 
                MessageBox.Show("Cannot delete post that you didn't create!!!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
        }
        private bool isPostCreatorOrModifier(String post)
        {
            bool ans = false;
            try
            {
                ans = _manager.isPostOwnerOrModerator(_forum, _threadName, post, _controller.Username);
            }
            catch (Exception)
            {
                _controller.Logger.Info("Could not know if isPostOwnerOrModerator " + _controller.Username + "details from forum " + _forum + ",for thread" + _threadName + "looking for post" + post);
                MessageBox.Show("Server is down. Please Logout and try again in a few minutes");
            }

            return ans;
        }

        private void RemovePostButtom_Click(object sender, EventArgs e)
        {
            if (PostsListBox.Items.Count == 0)
            {
                MessageBox.Show("There are no post to remove");
                return;
            }
            if (PostsListBox.SelectedIndex < 0 || PostsListBox.SelectedIndex >= PostsListBox.Items.Count)
            {
                MessageBox.Show("Please select post.");
                return;
            }
            String post = (String)PostsListBox.Items[PostsListBox.SelectedIndex];
            
            if (isPostCreatorOrModifier(post))
            {
                DialogResult res = MessageBox.Show("Are you sure you want to delete this post?", "Delete post", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (res == System.Windows.Forms.DialogResult.Yes)
                {
                    String ans = "";
                   try 
	                {
                        ans = _manager.deletePost(_controller.Username, _forum, _threadName, post);
	                }
	                catch (Exception)
	                {
                        _controller.Logger.Info(_controller.Username + " Could not deletePost " + post + " from forum " + _forum + ",for thread" + _threadName);
                        MessageBox.Show("Server is down. Please Logout and try again in a few minutes");
	                } 
                    refreshPostList();
                    MessageBox.Show(ans);
                }
            }
            else
                MessageBox.Show("Cannot delete post that you didn't create!!!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

        }
     
        private void ViewPostButton_Click_1(object sender, EventArgs e)
        {
            if (PostsListBox.Items.Count == 0)
            {
                MessageBox.Show("There are no post to view");
                return;
            }
            if (PostsListBox.SelectedIndex < 0 || PostsListBox.SelectedIndex >= PostsListBox.Items.Count)
            {
                MessageBox.Show("Please select post.");
                return;
            }
            this.Visible = false;
            int index = PostsListBox.SelectedIndex;
            String postName = (String)(PostsListBox.Items[index]);
            String toParse = "";
            try 
	        {
                toParse = _manager.getPostDetails(_forum, _threadName, postName);
	        }
	        catch (Exception)
	        {
                _controller.Logger.Info(_controller.Username + " Could not getPostDetails " + postName + " from forum " + _forum + ",for thread" + _threadName);
                MessageBox.Show("Server is down. Please Logout and try again in a few minutes");
	        }
            String[] details = toParse.Split('~');
            String header = details[0];
            String content = details[1];
            new ViewEditPost(_controller, ref _manager, _controller.Username, _forum, _threadName, header, content, true).Visible = true;
        }


        delegate void RefeshView();
        public void update()
        {
            if (this.PostsListBox.InvokeRequired)
            {
                RefeshView updateView = new RefeshView(refreshPostList);
                this.Invoke(updateView, new object[] { });
            }
            else
            {
                refreshPostList();
            }

        }

        delegate void RefeshNotifications();
        public void updateNotifications()
        {
            if (this.PostsListBox.InvokeRequired)
            {
                RefeshNotifications updateNoti = new RefeshNotifications(getNotifications);
                this.Invoke(updateNoti, new object[] { });
            }
            else
            {
                getNotifications();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            getNotifications();
        }

        private void getNotifications()
        {
            List<Notification> notifications = _controller.getNotifications();
            //for(int notificationIndex = notifications.Count - 1; notificationIndex > 
        }

        private void backButton_Click(object sender, EventArgs e)
        {
            ThreadsFrame tf = (ThreadsFrame)(_controller.popForm());
            tf.refreshThreads();
            tf.Show();
            //tf.Visible = true;
            this.Dispose(false);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            new ProfileFrame(ref _manager, ref _controller, _controller.Username).Visible = true;
        }

        private void PostsFrame_Load(object sender, EventArgs e)
        {
            Location = _controller.peekForm().Location;
        }

    }
}
